package com.jingxuan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingxuan.common.exception.BusinessException;
import com.jingxuan.common.result.ResultCode;
import com.jingxuan.dto.request.AddCommentRequest;
import com.jingxuan.dto.request.GetCommentsRequest;
import com.jingxuan.dto.response.AddCommentsResponse;
import com.jingxuan.dto.response.Commenter;
import com.jingxuan.dto.response.GetCommentsResponse;
import com.jingxuan.entity.Comment;
import com.jingxuan.entity.Product;
import com.jingxuan.entity.User;
import com.jingxuan.mapper.CommentsMapper;
import com.jingxuan.mapper.ProductsMapper;
import com.jingxuan.mapper.UserMapper;
import com.jingxuan.service.CommentsService;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class CommentsServiceImpl implements CommentsService {
    
    @Autowired
    private CommentsMapper commentsMapper;

    @Autowired
    private ProductsMapper productsMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public AddCommentsResponse addComment(String productId, AddCommentRequest request) {
        log.info("添加评论，商品ID：{}，用户ID：{}", productId, request.getUserId());
        
        // 验证商品是否存在
        Product product = productsMapper.selectById(productId);
        if (product == null) {
            log.error("商品不存在，商品ID：{}", productId);
            throw new BusinessException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        // 验证用户是否存在，并获取用户名
        User user = userMapper.selectById(request.getUserId());
        if (user == null) {
            log.error("用户不存在，用户ID：{}", request.getUserId());
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        
        // 构建评论对象
        Comment comment = new Comment();
        comment.setUserId(request.getUserId());
        comment.setUserName(user.getUserName());
        comment.setProductId(productId);
        comment.setContent(request.getContent());
        comment.setRating(request.getRating());
        comment.setLikeCount(0);
        
        // 插入数据库
        int result = commentsMapper.insertComment(comment);
        if (result <= 0) {
            log.error("评论添加失败");
            throw new BusinessException(ResultCode.DATABASE_ERROR);
        }
        
        log.info("评论添加成功，评论ID：{}", comment.getId());
        
        // 构建返回对象
        AddCommentsResponse response = new AddCommentsResponse();
        response.setCommentId(comment.getId());
        response.setProductId(productId);
        response.setContent(comment.getContent());
        response.setRating(comment.getRating());
        response.setPublishDate(comment.getPublishDate());
        
        Commenter commenter = new Commenter();
        commenter.setUserId(user.getId());
        commenter.setUserName(user.getUserName());
        response.setCommenter(commenter);
        
        return response;
    }

    @Override
    public GetCommentsResponse getComments(String productId, GetCommentsRequest request) {
        log.info("查询商品评论，商品ID：{}，页码：{}，每页条数：{}", 
                 productId, request.getPage(), request.getPageSize());
        
        // 验证商品是否存在
        Product product = productsMapper.selectById(productId);
        if (product == null) {
            log.error("商品不存在，商品ID：{}", productId);
            throw new BusinessException(ResultCode.PRODUCT_NOT_FOUND);
        }
        
        // 设置默认分页参数
        Integer page = request.getPage() != null ? request.getPage() : 1;
        Integer pageSize = request.getPageSize() != null ? request.getPageSize() : 10;
        Integer offset = (page - 1) * pageSize;
        
        // 查询评论列表
        List<Comment> comments = commentsMapper.selectCommentsByProductId(productId, offset, pageSize);
        
        // 查询总数
        int totalCount = commentsMapper.countCommentsByProductId(productId);
    
        // 转换为响应对象
        List<AddCommentsResponse> commentResponses = new ArrayList<>();
        for (Comment comment : comments) {
            AddCommentsResponse commentResponse = convertToResponse(comment);
            commentResponses.add(commentResponse);
        }
        
        // 构建返回对象
        GetCommentsResponse response = new GetCommentsResponse();
        response.setComments(commentResponses);
        response.setTotalCount(totalCount);
        response.setPage(page);
        response.setPageSize(pageSize);
        
        log.info("查询商品评论成功，总数：{}", totalCount);
        return response;
    }

    @Override
    public GetCommentsResponse getMyComments(Long userId, GetCommentsRequest request) {
        log.info("查询用户评论，用户ID：{}，页码：{}，每页条数：{}", 
                 userId, request.getPage(), request.getPageSize());
        
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.error("用户不存在，用户ID：{}", userId);
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }
        
        // 设置默认分页参数
        Integer page = request.getPage() != null ? request.getPage() : 1;
        Integer pageSize = request.getPageSize() != null ? request.getPageSize() : 10;
        Integer offset = (page - 1) * pageSize;
        
        // 查询评论列表
        List<Comment> comments = commentsMapper.selectCommentsByUserId(userId, offset, pageSize);
        
        // 查询总数
        int totalCount = commentsMapper.countCommentsByUserId(userId);
        
        // 转换为响应对象
        List<AddCommentsResponse> commentResponses = new ArrayList<>();
        for (Comment comment : comments) {
            AddCommentsResponse commentResponse = convertToResponse(comment);
            commentResponses.add(commentResponse);
        }
        
        // 构建返回对象
        GetCommentsResponse response = new GetCommentsResponse();
        response.setComments(commentResponses);
        response.setTotalCount(totalCount);
        response.setPage(page);
        response.setPageSize(pageSize);
        
        log.info("查询用户评论成功，总数：{}", totalCount);
        return response;
    }
    
    /**
     * 将Comment实体转换为AddCommentsResponse
     */
    private AddCommentsResponse convertToResponse(Comment comment) {
        AddCommentsResponse response = new AddCommentsResponse();
        response.setCommentId(comment.getId());
        response.setProductId(comment.getProductId());
        response.setContent(comment.getContent());
        response.setRating(comment.getRating());
        response.setPublishDate(comment.getPublishDate());
        
        Commenter commenter = new Commenter();
        commenter.setUserId(comment.getUserId());
        commenter.setUserName(comment.getUserName());
        response.setCommenter(commenter);
        
        return response;
    }

}
